/**
 *
 */
package cn.com.generaldata.os.report.check;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.com.generaldata.os.pojo.mvc.Report;
import cn.com.generaldata.os.pojo.mvc.Row;
import cn.com.generaldata.os.service.intf.ReportServiceInterface;
import cn.com.generaldata.os.util.BeanLoader;

/**
 * @author acer
 * 
 */
public class ReportCheckHandler {
	private static Log log = LogFactory.getLog(ReportCheckHandler.class);
	private static final String log_header = "[ReportCheckHandler]";

	private static String ReportTypeYear = "S01,S03,S04,S05,S06,S07,S08,S10,S13,S16,S19,S20,S21,S23,S24,S27,S28,S29,S32,S33,S34,S35,S36,S37,S38";
	private static String ReportTypeQuarter = "S42,S43,S44,S45,S46";
	private static String ReportTypeHalfYear = "A02-1,A02-2";
	private static Map<String, String> ReportCompareProperties = null;

	private static ReportServiceInterface reportIntf = null;

	private static byte REPORT_TB_LE = 1;
	private static byte REPORT_HB_LE = 2;
	private static byte REPORT_TB_GE = 3;
	private static byte REPORT_HB_GE = 4;

	static {
		initReportCompareProperties();

		reportIntf = (ReportServiceInterface) BeanLoader.loadBean("reportService");
	}

	private static void initReportCompareProperties() {
		ReportCompareProperties = new HashMap<String, String>();
		ReportCompareProperties.put("S01", "F4");
		ReportCompareProperties.put("S03", "F3,F4,F5");
		ReportCompareProperties.put("S04", "F4");
		ReportCompareProperties.put("S05", "F4,F5");
		ReportCompareProperties.put("S06", "F4");
		ReportCompareProperties.put("S07", "F4");
		ReportCompareProperties.put("S08", "F4");
		ReportCompareProperties.put("S10", "F4");
		ReportCompareProperties.put("S13", "F4");
		ReportCompareProperties.put("S16", "F2,F3,F4,F5");
		ReportCompareProperties.put("S19", "F4");
		ReportCompareProperties.put("S20", "F4");
		ReportCompareProperties.put("S21", "F4");
		ReportCompareProperties.put("S23", "F5");
		ReportCompareProperties.put("S24", "F5");
		ReportCompareProperties.put("S27", "F6");
		ReportCompareProperties.put("S28", "F6");
		ReportCompareProperties.put("S29", "F4");
		ReportCompareProperties.put("S32", "F4");
		ReportCompareProperties.put("S33", "F6");
		ReportCompareProperties.put("S34", "F4,F5,F6,F7");
		ReportCompareProperties.put("S35", "F4,F5,F6,F7,F8");
		ReportCompareProperties.put("S36", "F4,F5,F6,F7,F8");
		ReportCompareProperties.put("S37", "F4");
		ReportCompareProperties.put("S38", "F5");
		ReportCompareProperties.put("A02-1", "F3,F4");
		ReportCompareProperties.put("A02-2", "F4");
	}

	private static boolean isCompareProperty(String reportTypeCode, String propertyName) {
		if (null == reportTypeCode || reportTypeCode.trim().length() == 0) {
			return false;
		}
		if (null == propertyName || propertyName.trim().length() == 0) {
			return false;
		}

		String properties = ReportCompareProperties.get(reportTypeCode);
		if (null == properties || properties.trim().length() == 0) {
			return false;
		}

		return properties.indexOf(propertyName) >= 0;
	}

	private static boolean inReportTypeYear(String reportTypeCode) {
		if (null == reportTypeCode || reportTypeCode.trim().length() == 0) {
			return false;
		}

		return ReportTypeYear.indexOf(reportTypeCode) >= 0;
	}

	private static boolean inReportTypeQuarter(String reportTypeCode) {
		if (null == reportTypeCode || reportTypeCode.trim().length() == 0) {
			return false;
		}

		return ReportTypeQuarter.indexOf(reportTypeCode) >= 0;
	}

	private static boolean inReportTypeHalfYear(String reportTypeCode) {
		if (null == reportTypeCode || reportTypeCode.trim().length() == 0) {
			return false;
		}

		return ReportTypeHalfYear.indexOf(reportTypeCode) >= 0;
	}

	private static String getReportTitle(String reportTypeCode) {
		if ("S01".equalsIgnoreCase(reportTypeCode)) {
			return "沿海区域海洋行政管理机构情况";
		} else if ("S02".equalsIgnoreCase(reportTypeCode)) {
			return "沿海区域主要社会经济指标";
		} else if ("S03".equalsIgnoreCase(reportTypeCode)) {
			return "沿海区域主要海洋产业基本情况";
		} else if ("S04".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区海洋渔业生产及渔民收入基本情况";
		} else if ("S05".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区海洋捕捞、养殖基本情况";
		} else if ("S06".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区海洋机动渔船拥有量";
		} else if ("S07".equalsIgnoreCase(reportTypeCode)) {
			return "海洋油气勘探工作量";
		} else if ("S08".equalsIgnoreCase(reportTypeCode)) {
			return "海洋油田生产井概况";
		} else if ("S09".equalsIgnoreCase(reportTypeCode)) {
			return "海洋矿业生产情况";
		} else if ("S10".equalsIgnoreCase(reportTypeCode)) {
			return "海洋盐业生产情况";
		} else if ("S11".equalsIgnoreCase(reportTypeCode)) {
			return "海洋化工企业生产情况";
		} else if ("S12".equalsIgnoreCase(reportTypeCode)) {
			return "海洋生物医药企业生产情况";
		} else if ("S13".equalsIgnoreCase(reportTypeCode)) {
			return "海洋船舶工业生产情况";
		} else if ("S14".equalsIgnoreCase(reportTypeCode)) {
			return "海洋电力企业生产情况";
		} else if ("S15".equalsIgnoreCase(reportTypeCode)) {
			return "海洋电力项目建设情况";
		} else if ("S16".equalsIgnoreCase(reportTypeCode)) {
			return "沿海城市海水利用情况";
		} else if ("S17".equalsIgnoreCase(reportTypeCode)) {
			return "沿海城市海水利用项目情况";
		} else if ("S18".equalsIgnoreCase(reportTypeCode)) {
			return "海洋工程建筑项目投资情况";
		} else if ("S19".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区海洋客货运输量和周转量";
		} else if ("S20".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区客货吞吐量、集装箱运量和吞吐量情况";
		} else if ("S21".equalsIgnoreCase(reportTypeCode)) {
			return "海洋运输船舶拥有量";
		} else if ("S22".equalsIgnoreCase(reportTypeCode)) {
			return "沿海主要港口生产用码头泊位";
		} else if ("S23".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区入境和国内旅游者情况";
		} else if ("S24".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区星级饭店旅游接待能力和旅行社情况";
		} else if ("S25".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区其他海洋产业情况";
		} else if ("S26".equalsIgnoreCase(reportTypeCode)) {
			return "海洋对外贸易情况";
		} else if ("S27".equalsIgnoreCase(reportTypeCode)) {
			return "海洋教育情况";
		} else if ("S28".equalsIgnoreCase(reportTypeCode)) {
			return "海洋科研情况";
		} else if ("S29".equalsIgnoreCase(reportTypeCode)) {
			return "沿海海滨观测台站分布情况";
		} else if ("S30".equalsIgnoreCase(reportTypeCode)) {
			return "主要海上活动船舶";
		} else if ("S31".equalsIgnoreCase(reportTypeCode)) {
			return "海洋灾害和环境事故情况";
		} else if ("S32".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区废弃物海洋倾倒情况";
		} else if ("S33".equalsIgnoreCase(reportTypeCode)) {
			return "海洋类型保护区建设情况";
		} else if ("S34".equalsIgnoreCase(reportTypeCode)) {
			return "海水水质监测结果";
		} else if ("S35".equalsIgnoreCase(reportTypeCode)) {
			return "海水水质评价结果";
		} else if ("S36".equalsIgnoreCase(reportTypeCode)) {
			return "海洋石油勘探开发污染物排放入海情况";
		} else if ("S37".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区（城市）工业废水排放情况";
		} else if ("S38".equalsIgnoreCase(reportTypeCode)) {
			return "沿海地区（城市）工业固体废物排放、处理、利用及污染治理项目情况";
		} else if ("S39".equalsIgnoreCase(reportTypeCode)) {
			return "海上救捞情况";
		} else if ("S40".equalsIgnoreCase(reportTypeCode)) {
			return "海洋行政复议案件情况";
		} else if ("S41".equalsIgnoreCase(reportTypeCode)) {
			return "海洋行政应诉案件情况";
		} else if ("S42".equalsIgnoreCase(reportTypeCode)) {
			return "海域使用管理情况";
		} else if ("S43".equalsIgnoreCase(reportTypeCode)) {
			return "海洋环境保护管理情况";
		} else if ("S44".equalsIgnoreCase(reportTypeCode)) {
			return "海洋执法检查情况";
		} else if ("S45".equalsIgnoreCase(reportTypeCode)) {
			return "海洋行政处罚情况";
		} else if ("S46".equalsIgnoreCase(reportTypeCode)) {
			return "海洋权益维护情况";
		} else if ("A02-1".equalsIgnoreCase(reportTypeCode)) {
			return "海洋经济主要产业产值";
		} else if ("A02-2".equalsIgnoreCase(reportTypeCode)) {
			return "海洋经济主要产业产量（服务量）";
		} else {
			return "未知报表";
		}
	}

	public static String checkReport(String reportId, String rules) {
		StringBuffer sb = new StringBuffer();
		if (null == reportId || reportId.trim().length() == 0) {
			log.error(log_header + "[checkReport]reportId is null");
			sb.append("错误：报表编码为空值！\r\n");
		}
		Report report = reportIntf.queryMVCReportById(reportId);
		if (null == report) {
			log.error(log_header + "[checkReport]report not found");
			sb.append("错误： 报表不存在！\r\n");
			return sb.toString();
		}
		if (null == report.getReportTypeCode() || report.getReportTypeCode().trim().length() == 0) {
			log.error(log_header + "[checkReport]reportTypeCode error");
			sb.append("错误：报表类型编码不正确！\r\n");
		}

		if (!inReportTypeYear(report.getReportTypeCode()) && !inReportTypeQuarter(report.getReportTypeCode())
				&& !inReportTypeHalfYear(report.getReportTypeCode())) {
			log.error(log_header + "[checkReport]Report can't be checked!");
			sb.append("报表：" + getReportTitle(report.getReportTypeCode()) + ", 动态表无法审核！\r\n");
		}
		String[] rs = rules.split(",");
		for (String rule : rs) {
			StringBuffer b = checkRule(report, Byte.parseByte(rule));
			sb.append(b);
		}

		return sb.toString();
	}

	private static StringBuffer checkRule(Report report, byte ruleCode) {
		StringBuffer result = new StringBuffer();
		Report lastReport = null;
		if (REPORT_TB_LE == ruleCode || REPORT_TB_GE == ruleCode) {
			// get last report
			String lastYear = (new Integer(Integer.parseInt(report.getReportYear()) - 1)).toString();
			lastReport = reportIntf.queryReport2AutoValidate(report.getReportUnit(), report.getReportTypeCode(),
					lastYear, report.getReportQuarter());
		} else {
			String lastQuarter = null;
			String lastYear = null;
			if (null == report.getReportQuarter() || report.getReportQuarter().trim().length() == 0) {
				return result.append("错误：报表不是季表或半年表，无法进行环比！\r\n");
			}
			if ("1".equals(report.getReportQuarter().trim())) {
				lastYear = (new Integer(Integer.parseInt(report.getReportYear()) - 1)).toString();
				lastQuarter = "4";
			} else if ("2".equals(report.getReportQuarter().trim()) || "3".equals(report.getReportQuarter().trim())
					|| "4".equals(report.getReportQuarter().trim())) {
				lastYear = report.getReportYear();
				lastQuarter = (new Integer(Integer.parseInt(report.getReportQuarter()) - 1)).toString();
				lastReport = reportIntf.queryReport2AutoValidate(report.getReportUnit(), report.getReportTypeCode(),
						lastYear, lastQuarter);
			} else if ("上".equals(report.getReportQuarter().trim())) {
				lastYear = (new Integer(Integer.parseInt(report.getReportYear()) - 1)).toString();
				lastQuarter = "下";
				lastReport = reportIntf.queryReport2AutoValidate(report.getReportUnit(), report.getReportTypeCode(),
						lastYear, lastQuarter);
			} else if ("下".equals(report.getReportQuarter().trim())) {
				lastYear = report.getReportYear();
				lastQuarter = "上";
				lastReport = reportIntf.queryReport2AutoValidate(report.getReportUnit(), report.getReportTypeCode(),
						lastYear, lastQuarter);
			}
		}

		if (null == lastReport) {
			if (REPORT_TB_LE == ruleCode || REPORT_TB_GE == ruleCode) {
				return result.append("错误：同比报表未找到！\r\n");
			} else {
				return result.append("错误：环比报表未找到！\r\n");
			}
		}

		for (int i = 0, size = report.getRows().size(); i < size; i++) {
			Row row = report.getRows().get(i);
			Row lastRow = lastReport.getRows().get(i);
			String label = "";

			if (isCompareProperty(report.getReportTypeCode(), "F1")) {
				result.append(compareProperty(label, row.getF1(), lastRow.getF1(), ruleCode));
			} else {
				if (null != row.getF1() && row.getF1().trim().length() > 0) {
					String v = row.getF1().replace("　", "");
					label += " " + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F2")) {
				result.append(compareProperty(label, row.getF2(), lastRow.getF2(), ruleCode));
			} else {
				if (null != row.getF2() && row.getF2().trim().length() > 0) {
					String v = row.getF2().replace("　", "");
					label += " " + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F3")) {
				result.append(compareProperty(label, row.getF3(), lastRow.getF3(), ruleCode));
			} else {
				if (null != row.getF3() && row.getF3().trim().length() > 0) {
					String v = row.getF3().replace("　", "");
					label += " " + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F4")) {
				result.append(compareProperty(label, row.getF4(), lastRow.getF4(), ruleCode));
			} else {
				if (null != row.getF4() && row.getF4().trim().length() > 0) {
					String v = row.getF4().replace("　", "");
					label += " " + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F5")) {
				result.append(compareProperty(label, row.getF5(), lastRow.getF5(), ruleCode));
			} else {
				if (null != row.getF5() && row.getF5().trim().length() > 0) {
					String v = row.getF5().replace("　", "");
					label += " " + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F6")) {
				result.append(compareProperty(label, row.getF6(), lastRow.getF6(), ruleCode));
			} else {
				if (null != row.getF6() && row.getF6().trim().length() > 0) {
					String v = row.getF6().replace("　", "");
					label += " " + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F7")) {
				result.append(compareProperty(label, row.getF7(), lastRow.getF7(), ruleCode));
			} else {
				if (null != row.getF7() && row.getF7().trim().length() > 0) {
					String v = row.getF7().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F8")) {
				result.append(compareProperty(label, row.getF8(), lastRow.getF8(), ruleCode));
			} else {
				if (null != row.getF8() && row.getF8().trim().length() > 0) {
					String v = row.getF8().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F9")) {
				result.append(compareProperty(label, row.getF9(), lastRow.getF9(), ruleCode));
			} else {
				if (null != row.getF9() && row.getF9().trim().length() > 0) {
					String v = row.getF9().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F10")) {
				result.append(compareProperty(label, row.getF10(), lastRow.getF10(), ruleCode));
			} else {
				if (null != row.getF10() && row.getF10().trim().length() > 0) {
					String v = row.getF10().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F11")) {
				result.append(compareProperty(label, row.getF11(), lastRow.getF11(), ruleCode));
			} else {
				if (null != row.getF11() && row.getF11().trim().length() > 0) {
					String v = row.getF11().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F12")) {
				result.append(compareProperty(label, row.getF12(), lastRow.getF12(), ruleCode));
			} else {
				if (null != row.getF12() && row.getF12().trim().length() > 0) {
					String v = row.getF12().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F13")) {
				result.append(compareProperty(label, row.getF13(), lastRow.getF13(), ruleCode));
			} else {
				if (null != row.getF13() && row.getF13().trim().length() > 0) {
					String v = row.getF13().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F14")) {
				result.append(compareProperty(label, row.getF14(), lastRow.getF14(), ruleCode));
			} else {
				if (null != row.getF14() && row.getF14().trim().length() > 0) {
					String v = row.getF14().replace("　", "");
					label += "," + v;
				}
			}

			if (isCompareProperty(report.getReportTypeCode(), "F15")) {
				result.append(compareProperty(label, row.getF15(), lastRow.getF15(), ruleCode));
			} else {
				if (null != row.getF15() && row.getF15().trim().length() > 0) {
					String v = row.getF15().replace("　", "");
					label += "," + v;
				}
			}

		}

		return result;
	}

	private static String compareProperty(String label, String F, String lastF, byte ruleCode) {
		try {
			if (null == F || F.trim().length() == 0 || null == lastF || lastF.trim().length() == 0) {
				return "";
			}

			Double v = Double.parseDouble(F);
			Double lastV = Double.parseDouble(lastF);
			if (REPORT_TB_LE == ruleCode) {
				if (v > lastV) {
					return "同比小于等于对比错误：" + label + "，当期报表值，" + v + "，上期报表值，" + lastV + "\r\n";
				}
			} else if (REPORT_HB_LE == ruleCode) {
				if (v > lastV) {
					return "环比小于等于对比错误：" + label + "，当期报表值，" + v + "，上期报表值，" + lastV + "\r\n";
				}

			} else if (REPORT_TB_GE == ruleCode) {
				if (v < lastV) {
					return "同比大于等于对比错误：" + label + "，当期报表值，" + v + "，上期报表值，" + lastV + "\r\n";
				}
			} else if (REPORT_HB_GE == ruleCode) {
				if (v < lastV) {
					return "环比大于等于对比错误：" + label + "，当期报表值，" + v + "，上期报表值，" + lastV + "\r\n";
				}
			}
			return "";
		} catch (Exception ex) {
			log.error(log_header + "[compareProperty]Exception: ", ex);
			return "错误：属性值不是数值类型！\r\n";
		}
	}
}
